package bajo.src;

import java.util.Vector;

import javax.microedition.io.HttpConnection;

import net.rim.blackberry.api.browser.URLEncodedPostData;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

public class LoginScreen extends MainScreen {
	
	private LoginScreen me;
	
	/* Labels and text boxes */
	private TextBoxField usernameTxt;
	private TextBoxField passwordTxt;
	private ButtonField loginButton;
	private ButtonField registerButton;
	private LabelField username;
	private LabelField password;
	private LabelField title;
	
	/* Used to manage the layout of the screen */
	private HorizontalFieldManager horManager;
	private HorizontalFieldManager horButtonManager;
	private VerticalFieldManager verManagerTxt;
	private VerticalFieldManager verManagerLabel;

	private String user;
	private String pass;
	private final String TITLE = "BAJO!";
	
	/* Constructor */
	public LoginScreen() {		
		usernameTxt = new TextBoxField(25, 200, false);
		passwordTxt = new TextBoxField(25, 200, true);
		init();
	}
	
	/* Constructor */
	public LoginScreen(String initUsername, String initPassword) {
		usernameTxt = new TextBoxField(25, 200, false, initUsername);
		passwordTxt = new TextBoxField(25, 200, true, initPassword);
		init();
	}
	
	private void init() {
		me = this;
		
		horManager = new HorizontalFieldManager();
		horButtonManager = new HorizontalFieldManager();
		verManagerTxt = new VerticalFieldManager();
		verManagerLabel = new VerticalFieldManager();
		
		title = new LabelField(TITLE, Manager.FIELD_HCENTER);
		title.setFont(Font.getDefault().derive(Font.BOLD, 36));
		
		username = new LabelField("Username: ");
		password = new LabelField("Password: ");
		
		// Variables for text box.
		verManagerTxt.add(usernameTxt);
		verManagerTxt.add(passwordTxt);
		
		// Variables for the label for the text box.
		verManagerLabel.add(username);
		verManagerLabel.add(password);
		
		horManager.add(verManagerLabel);
		horManager.add(verManagerTxt);
		
		// Login button.
		loginButton = new ButtonField("Login");
		loginButton.setChangeListener(new FieldChangeListener(){
			public void fieldChanged(Field field, int context) {
				if (field.equals(loginButton)) {
					user = usernameTxt.getText();
					pass = passwordTxt.getText();
					// TODO: Check the given user name and password is correct.
					
					URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
					postData.append("userId", user);
					postData.append("password", pass);
					HTTPDataThread sendThread = new HTTPDataThread(Constants.BASE_TOMCAT_ADDR + Constants.LOGIN_SERVLET,
														postData, HttpConnection.POST);
					sendThread.start();
					
					String[] retData = null;
					synchronized (HTTPDataThread.global_lock) {
						retData = HTTPDataThread.copyData();
					}
					String[] isValidUser = retData;
					
					//TODO: check for valid user
					if (isValidUser[0].equals("0")){
						//non existing user
						Dialog.alert("Not Existing User!\n Please Register!");
						UiApplication.getUiApplication().pushScreen(
								new RegisterPage(me));
					
					}else if (isValidUser[0].equals("1")){
						//valid user
						sendThread = new HTTPDataThread(
								Constants.BASE_TOMCAT_ADDR
										+ Constants.OFFERED_COURSE_SERVLET,
								null, HttpConnection.GET);
						sendThread.start();
						try {
							sendThread.join();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						retData = null;
						synchronized (HTTPDataThread.global_lock) {
							retData = HTTPDataThread.copyData();
						}
						String[] courses = retData;
						UiApplication.getUiApplication().pushScreen(
								new MainPage(user, courses));
					} else if (isValidUser[0].equals("2")) {
						// wrong password
						Dialog.alert("Wrong Password!\n Please Try Again!");
						passwordTxt.setText("");
						passwordTxt.setFocus();
					}
				}
			}
		});

		// Register button.
		registerButton = new ButtonField("Register");
		registerButton.setChangeListener(new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				UiApplication.getUiApplication().pushScreen(
						new RegisterPage(me));
			}
		});

		horButtonManager.add(loginButton);
		horButtonManager.add(registerButton);
		
		add(title);
		add(horManager);
		add(horButtonManager);
	}
	
	/*
	 * Overridden function to get rid of the menu when switching to a 
	 * new main screen.
	 */
	public boolean onMenu(int instance) {
		return true;
	}

	/*
	 * Overridden function used to get rid of the save prompt
	 * when exiting the MainScreen.
	 */
	protected boolean onSavePrompt(){
		return true;
	}
	
	public TextBoxField getUserNameField(){
		return this.usernameTxt;
	}
	public TextBoxField getPasswordField(){
		return this.passwordTxt;
	}
}

